<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top:10px">
      <el-alert
        title="注意:只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row style="margin-top:10px">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            :options="parentList"
            :props="cateProps"
            v-model="selectedCateKeys"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <template>
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
        >
          <!-- 动态参数框 -->
          <el-tab-pane
            label="动态参数"
            name="many"
          >
            <el-button
              type="primary"
              :disabled="isBtnDisabled"
              @click="rrr=true"
            >添加参数</el-button>
            <el-table
              :data="manyTableData"
              border
              style="width: 100%;margin-top:15px"
            >
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    closable
                    v-for="(item,i) in scope.row.attr_vals"
                    :key="i"
                  >{{item}}</el-tag>
                  <!-- 输入文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index"></el-table-column>
              <el-table-column
                prop="attr_name"
                label="参数名称"
              >
              </el-table-column>

              <el-table-column
                prop="address"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    @click="showEdit(scope.row.attr_id)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    @click="deletes(scope.row.attr_id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 静态属性框 -->
          <el-tab-pane
            label="静态属性"
            name="only"
          >
            <el-button
              type="primary"
              :disabled="isBtnDisabled"
              @click="jjj=true"
            >添加属性</el-button>
            <el-table
              :data="onlyTableData"
              border
              style="width: 100%;margin-top:15px"
            >
               <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    closable
                    v-for="(item,i) in scope.row.attr_vals"
                    :key="i"
                  >{{item}}</el-tag>
                  <!-- 输入文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index"></el-table-column>
              <el-table-column
                prop="attr_name"
                label="属性名称"
              >
              </el-table-column>

              <el-table-column
                prop="address"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    @click="showEdit(scope.row.attr_id)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    @click="deletes(scope.row.attr_id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>

    <!-- 添加动态参数框 -->
    <el-dialog
      title="添加动态参数"
      :visible.sync="rrr"
      width="30%"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="参数名称"
          prop="attr_name"
        >
          <el-input v-model="ruleForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('ruleForm')"
          >添加</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    <!-- 静态属性添加 -->
    <el-dialog
      title="添加静态属性"
      :visible.sync="jjj"
      width="30%"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="参数名称"
          prop="attr_name"
        >
          <el-input v-model="ruleForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('ruleForm')"
          >添加</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    <!-- 修改动态参数 -->
    <el-dialog
      title="修改动态参数"
      :visible.sync="sss"
      width="30%"
      @close="ppp()"
    >
      <el-form
        :model="xiugaiList"
        :rules="xiugaiListRules"
        ref="xiugaiList"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="参数名称"
          prop="attr_name"
        >
          <el-input v-model="xiugaiList.attr_name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="tijiao()"
          >添加</el-button>
          <el-button @click="ppp()">重置</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    <!-- 修改静态属性 -->
    <el-dialog
      title="修改静态属性"
      :visible.sync="aaa"
      width="30%"
      @close="ppp()"
    >
      <el-form
        :model="xiugaiList"
        :rules="xiugaiListRules"
        ref="xiugaiList"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="参数名称"
          prop="attr_name"
        >
          <el-input v-model="xiugaiList.attr_name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="tijiao()"
          >添加</el-button>
          <el-button @click="ppp()">重置</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      ruleForm: {
        attr_name: "",
      },
      xiugaiList: {},
      xiugaiListRules: {
        attr_name: [
          { required: true, message: "请输入动态参数名称", trigger: "blur" },
        ],
      },
      parentList: [],
      fenlei: [],
      selectList: {},
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      selectedCateKeys: [],
      activeName: "many",
      manyTableData: [],
      onlyTableData: [],
      rrr: false,
      jjj: false,
      sss: false,
      aaa: false,
      inputValue: "",
      inputVisible: false,
      rules: {
        attr_name: [
          { required: true, message: "请输入动态参数名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.handleSelect();
  },
  mounted() {},
  methods: {
    //获取商品分类
    async handleSelect() {
      const { data: res } = await this.$http.get("categories");
      this.parentList = res.data;
      // console.log(this.parentList);
      // console.log(res);
    },

    //获取动态或者静态属性
    async getParamsData() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = [];
        this.manyTableData=[];
        this.onlyTableData=[]
        return;
      }
      console.log(this.selectedCateKeys);

      const res = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName },
      });

      // console.log(res.data.data);
      res.data.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        //控制文本框的显影
        item.inputVisible = false;
        item.inputValue = "";
      });

      if (this.activeName === "many") {
        this.manyTableData = res.data.data;
        console.log(this.manyTableData);
      } else {
        this.onlyTableData = res.data.data;
        console.log(this.onlyTableData);
      }
    },
    handleChange() {
      this.getParamsData();
    },
    handleClick() {
      this.getParamsData();
      // console.log(this.activeName);
    },
    //编辑参数   根据id查询参数
    async showEdit(attr_id) {
      const res = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: { attr_sela: this.activeName },
        }
      );
      console.log(res.data.data);
      this.xiugaiList = res.data.data;
      this.sss = true;
      this.aaa = true;
    },

    //提交修改
    tijiao() {
      this.$refs.xiugaiList.validate(async (valid) => {
        if (!valid) return;
        const res = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.xiugaiList.attr_id}`,
          {
            attr_name: this.xiugaiList.attr_name,
            attr_sel: this.activeName,
          }
        );
        this.getParamsData();
        this.sss = false;
        this.aaa = false;
      });
    },

    //删除属性
    deletes(attr_id) {
      this.$confirm("此操作将删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$http.delete(
            `categories/${this.cateId}/attributes/${attr_id}`
          );
          // console.log(res.data);
          this.getParamsData();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //提交表单
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await this.$http.post(
            `categories/${this.cateId}/attributes`,
            {
              attr_name: this.ruleForm.attr_name,
              attr_sel: this.activeName,
            }
          );
          (this.rrr = false), (this.jjj = false);
          this.getParamsData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //提交修改表单
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await this.$http.post(
            `categories/${this.cateId}/attributes`,
            {
              attr_name: this.ruleForm.attr_name,
              attr_sel: this.activeName,
            }
          );
          (this.rrr = false), (this.jjj = false);
          this.getParamsData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //重置修改表单
    ppp() {
      this.$refs.xiugaiList.resetFields();
    },
    //文本框失去焦点 或enter 触发
 async   handleInputConfirm(row) {
      console.log("ok");
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false;
        row.inputValue = "";
        return
      }
      row.attr_vals.push(row.inputValue.trim())
        row.inputValue = "";
      row.inputVisible=false

      const res =await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(' ')
      })

      if(res.data.meta.status !==200){
        return this.$message.error('修改失败');
      }
      this.$message.success('修改成功')
      console.log(res.data);
    },
    showInput(row) {
      row.inputVisible = true;

      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
  },
  computed: {
    //是否禁用按钮
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    //当前选中的三级分类id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2];
      }
      return null;
    },
  },
};
</script>

<style scoped>
.el-tag {
  margin: 10px;
}
</style>
